<template>
  <CDialog
    title="追溯供应商场地数据"
    v-model:visible="dialogVisible"
    :loading="loading"
    confirmText="发送请求"
    cancelText="关闭"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <!-- <CAlert
      style="margin-bottom: 16px"
      size="simple"
      subtitle="该请求将通过邮件发出，请提醒供应商指定人员处理"
      type="info"
    ></CAlert> -->
    <el-form ref="formRef" :model="formState" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="供应商" prop="supplierName">
            <el-input v-model="formState.supplierName" type="text" placeholder="请输入" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="选择人员" prop="supplierUserIds">
            <el-select
              v-model="formState.supplierUserIds"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择"
            >
              <el-option
                v-for="item in supplierUserList"
                :key="item.userId"
                :label="item.realName"
                :value="item.userId"
              >
                <div class="g-flex-between-center">
                  <span class="select-option-title">{{ item.realName }}</span>
                  <span class="select-option-subtitle">{{ item.email }}</span>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料编码" prop="partCode">
            <el-input v-model="formState.partCode" type="text" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="物料名称" prop="partName">
            <el-input v-model="formState.partName" type="text" placeholder="请输入" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="功能单位" prop="num">
            <CDosageAndUnit
              placeholder="请输入"
              v-model:dosage="formState.num"
              v-model:unit="formState.unit"
              is-group
              unit-type="ALL"
            ></CDosageAndUnit>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="核算年份" prop="dataYear">
            <el-date-picker
              v-model="formState.dataYear"
              type="year"
              style="width: 100%"
              value-format="YYYY"
              placeholder="请选择"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="规格型号" prop="specification">
            <el-input v-model="formState.specification" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="补充说明" prop="remark">
            <el-input v-model="formState.remark" type="textarea" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>

<script lang="ts" setup name="MaterialDialog">
import { withDefaults, defineProps, defineEmits, computed, watch, reactive, ref, unref } from 'vue';
import { CDialog } from '@/components/CDialog';
import CDosageAndUnit from '@/businessComponents/CDosageAndUnit/index.vue';
import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import { CAlert } from '@/components/CAlert';
import {
  getSupplierOptions,
  getSupplierUserOptions,
  traceSupplierData
} from '@/apis/pcf/supplier/supplierList';
import type { ModelDetailResult } from '@/apis/pcf/myModel/model/modelManage';
import type { GetListBomTreeResult } from '@/apis/pcf/myModel/model/modelDetailModel';
import { modelUnitAllNoPcsOption } from '@/constants/unit';
interface MaterialDialogProps {
  visible: boolean;
  nodeNo: string;
  modelDetail?: ModelDetailResult;
  node?: GetListBomTreeResult;
}
const props = withDefaults(defineProps<MaterialDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);
const { createMessage } = useMessage();
const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      init();
    } else {
      formRef.value?.resetFields();
    }
  }
);

const formRef = ref();
const loading = ref(false);
/**
 * 表单内容
 */
const formState = reactive({
  supplierUserIds: [],
  supplierNo: '',
  supplierCode: '',
  supplierName: '',
  partCode: '',
  partName: '',
  num: '1',
  remark: '',
  unit: 'pcs',
  dataYear: '',
  specification: ''
});

const supplierUserList = ref<any[]>([]);
// const supplierList = ref<any[]>([]);

// const loadSupplierList = async () => {
//   let data = await getSupplierOptions();
//   supplierList.value = data ?? [];
// };

const changeSupplier = async () => {
  if (formState.supplierNo) {
    let userData = await getSupplierUserOptions(formState.supplierNo);
    supplierUserList.value = userData ?? [];
  }
};
/**
 * 初始化
 */
function init() {
  const { modelDetail, node } = unref(props);
  formState.dataYear = modelDetail?.accountYear || '';
  formState.partCode = node?.nodeCode || '';
  formState.partName = node?.nodeName || '';
  formState.specification = node?.remark ?? '';
  formState.unit = node?.dataType == 'ITEM' ? 'pcs' : node?.unit || 'kg';
  formState.supplierNo = node?.supplierNo || '';
  formState.supplierCode = node?.supplierCode || '';
  formState.supplierName = node?.supplierName || '';
  changeSupplier();
}

/**
 * 保存按钮
 */
function handleConfirm() {
  console.log('handleConfirm');
  formRef.value?.validate((valid: boolean, val: any) => {
    if (valid) {
      submitFlowReq();
    } else {
      const keys = Object.keys(val);
      formRef.value?.scrollToField(keys[0]);
    }
  });
}

/**
 * 接口请求
 */
async function submitFlowReq() {
  console.log('submitFlowReq');
  loading.value = true;
  try {
    const params = {
      ...formState,
      nodeNo: props.nodeNo as string
    };
    await traceSupplierData(params);
    createMessage.success('操作成功！');
    emits('refresh', props.nodeNo);
    dialogVisible.value = false;
    loading.value = false;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}
</script>
